from history import BilibiliAPI
import datetime
import tkinter as tk


class HistoryConsole(BilibiliAPI):
    def select_history(self, history_record):
        if history_record is None:
            # try use self.history
            history_record  = self.load_history()
        for h in history_record:
            # archive：稿件, pgc：番剧（影视）
            if h['history']['business'] != 'archive' and h['history']['business'] != 'pgc':
                self.print_magic('35', h['title'])
            else:
                self.print_magic('33' if h['progress'] < h['duration']/2 else '36', h['title'])
        

    # 36：青色， 33：黄色， 35：紫色
    def print_magic(self, color='36', content='', end='\n'):
        print("\033[1;"+ color +"m", end='')
        print(content, end='')
        print("\033[0m", end=end)


class HistoryGUI(tk.Frame):
    def __init__(self, master=None, history=None):
        super().__init__(master)
        self.master = master
        self.history = history
        self.frames = []
        self.enable = {}
        self.pack()
        self.create_widgets()
        

    def create_frame(self, name, history):
        frame = tk.Frame(self.hisFrame)
        frame.grid(row=0, column=len(self.frames), sticky=tk.W)
        self.frames.append(frame)

        label = tk.Label(frame, text=name)
        label.pack()
        scrollbar = tk.Scrollbar(frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        checklist = tk.Text(frame, width=50)
        checklist.pack()
        for h in history:
            self.enable[h['title']] = tk.IntVar(0)
            if name == '快看完了': self.enable[h['title']].set(1)
            checkbox = tk.Checkbutton(checklist, text=h['title'], width=50, anchor=tk.W, wraplength=300, borderwidth=1, justify='left', variable=self.enable[h['title']])
            checklist.window_create('end', window=checkbox)
        checklist.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=checklist.yview)
        # disable the widget so users can't insert text into it
        checklist.configure(state="disabled")


    def create_widgets(self):
        # make main frame
        self.hisFrame = tk.Frame(self)
        h1 = [h for h in self.history if h['history']['business'] in ['archive', 'pgc'] and h['progress'] >= h['duration']/2]
        self.create_frame('快看完了', h1)
        h0 = [h for h in self.history if h['history']['business'] in ['archive', 'pgc'] and h['progress'] < h['duration']/2]
        self.create_frame('没看多少', h0)
        h_article = [h for h in self.history if h['history']['business'] not in ['archive', 'pgc']]
        self.create_frame('文章和专栏', h_article)
        self.hisFrame.grid(row=0, column=0, sticky=tk.N)
        # make footer
        self.make_footer()


    def make_footer(self):
        self.footer = tk.Frame(self)
        self.submit = tk.Button(self.footer, text='导出', fg='red', command=self.submit_history)
        self.submit.grid(row=0, column=0, sticky=tk.E)
        self.quit = tk.Button(self.footer, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.grid(row=0, column=1, sticky=tk.W)
        self.footer.grid(row=1, column=0, sticky=tk.S)


    def submit_history(self):
        names = [h for h in self.enable if self.enable[h].get() != 0]
        selected = [h for h in self.history if h['title'] in names]
        with open('bilibili_history.md', 'w', encoding='utf-8') as fw:
            print('Write to: ', 'bilibili_history.md')
            fw.write('|  标题  | 作者 | 定位 | 标签 |\n')
            fw.write('|  ----  | ---- | ---- | ---- |\n')
            for h in selected:
                data = self.format_history(h)
                fw.write('|' + '|'.join([data['title'], data['author'], data['loc'], data['tags']]) + ' |\n')


    def format_history(self, history):
        # print(history)
        def combine(l1, l2):
            if len(l1(history)) == 0:
                return l2(history)
            elif len(l2(history)) == 0:
                return l1(history)
            else:
                l1(history) + ', ' + l2(history)        
        result = {
            # combine bvid or uri
            'loc': combine(lambda x:x['uri'], lambda x:x['history']['bvid']),
            'title': combine(lambda x:x['title'], lambda x:x['long_title']),
            'tags': combine(lambda x:x['tag_name'], lambda x:x['badge']),
            'author': history['author_name']
        }
        return result


if __name__ == "__main__":
    # how to use history console
    # hc = HistoryConsole()
    # hc.select_history()
    # how to use GUI module
    hg = HistoryGUI(master=tk.Tk(), history=BilibiliAPI().load_history())
    hg.mainloop()